package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.util.HttpUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.json.JSONObject;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

public class ActivityRegisterController {
    public VBox avatarUpload;
    @FXML
    public ImageView avatar;
    @FXML
    private TextField name;
    @FXML
    private DatePicker startDay,endDay;
    @FXML
    private ComboBox<String> type;
    @FXML
    private TextArea description;
    @FXML
    private ComboBox<Integer> hour11,hour12,hour21,hour22,minute11,minute12,minute21,minute22,second11,second12,second21,second22;
    @FXML
    public Button submit,submit1;
    @FXML
    public Label success,label;
    @FXML
    public HBox upload;
    private File selectedFile;

    public void initialize() {
        Globalvar.userToken ="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyMDI0OTk5OSIsImlhdCI6MTcxNzIxOTA2NiwiZXhwIjoxNzE3MjI3NzA2fQ" +
                ".zhUYxrzfiDVuJbqTxmyV-lr-j2OP4n7h4IyfMMtO_QHTrXfSzf0JDhcahRm2xRA9hnO5hr-xOQKR4a8DLlI19A";
        ObservableList<String> items1= FXCollections.observableArrayList("竞赛","志愿活动");
        type.setItems(items1);
        ObservableList<Integer> items2= FXCollections.observableArrayList(0,1,2);
        hour11.setItems(items2);
        ObservableList<Integer> items3= FXCollections.observableArrayList(0,1,2,3);
        hour12.setItems(items3);
        ObservableList<Integer> items4= FXCollections.observableArrayList(0,1,2,3,4,5);
        minute11.setItems(items4);
        ObservableList<Integer> items5= FXCollections.observableArrayList(0,1,2,3,4,5,6,7,8,9);
        minute12.setItems(items5);
        ObservableList<Integer> items6= FXCollections.observableArrayList(0,1,2,3,4,5);
        second11.setItems(items6);
        ObservableList<Integer> items7= FXCollections.observableArrayList(0,1,2,3,4,5,6,7,8,9);
        second12.setItems(items7);
        ObservableList<Integer> items8= FXCollections.observableArrayList(0,1,2);
        hour21.setItems(items8);
        ObservableList<Integer> items9= FXCollections.observableArrayList(0,1,2,3);
        hour22.setItems(items9);
        ObservableList<Integer> items10= FXCollections.observableArrayList(0,1,2,3,4,5);
        minute21.setItems(items10);
        ObservableList<Integer> items11= FXCollections.observableArrayList(0,1,2,3,4,5,6,7,8,9);
        minute22.setItems(items11);
        ObservableList<Integer> items12= FXCollections.observableArrayList(0,1,2,3,4,5);
        second21.setItems(items12);
        ObservableList<Integer> items13= FXCollections.observableArrayList(0,1,2,3,4,5,6,7,8,9);
        second22.setItems(items13);
        hour11.getSelectionModel().select(0);
        hour21.getSelectionModel().select(0);
        hour12.getSelectionModel().select(0);
        hour22.getSelectionModel().select(0);
        minute11.getSelectionModel().select(0);
        minute12.getSelectionModel().select(0);
        minute21.getSelectionModel().select(0);
        minute22.getSelectionModel().select(0);
        second11.getSelectionModel().select(0);
        second12.getSelectionModel().select(0);
        second21.getSelectionModel().select(0);
        second22.getSelectionModel().select(0);
        hour11.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                int selectedHour11 = newValue;

                ObservableList<Integer> updatedHour12Items = FXCollections.observableArrayList();
                int maxHour12Value = (selectedHour11 == 2) ? 3 : 9;

                for (int i = 0; i <= maxHour12Value; i++) {
                    updatedHour12Items.add(i);
                }

                hour12.setItems(updatedHour12Items);
            }
        });
        hour21.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                int selectedHour21 = newValue;

                ObservableList<Integer> updatedHour22Items = FXCollections.observableArrayList();
                int maxHour22Value = (selectedHour21 == 2) ? 3 : 9;

                for (int i = 0; i <= maxHour22Value; i++) {
                    updatedHour22Items.add(i);
                }

                hour22.setItems(updatedHour22Items);
            }
        });
        Circle clip = new Circle(avatar.getFitWidth() / 2, avatar.getFitHeight() / 2, Math.min(avatar.getFitWidth() , avatar.getFitHeight()) / 2);
        avatar.setClip(clip);
        avatarUpload.setOnMouseClicked(e->{
            FileChooser fileChooser = new FileChooser();
            selectedFile = fileChooser.showOpenDialog(null);
            Image img = new Image(selectedFile.toURI().toString());
            double wid = Math.min(img.getWidth() , img.getHeight());
            Rectangle2D viewport = new Rectangle2D(img.getWidth()/2 - wid/2, img.getHeight()/2 - wid/2, wid, wid);
            avatar.setViewport(viewport);
            avatar.setImage(new Image(selectedFile.toURI().toString()));
        });
    }

    public void activitySubmitButtonClick() {
        boolean nameEmpty = name.getText().isEmpty();
        boolean typeEmpty = type.getValue() == null;
        boolean startDayEmpty = startDay.getValue() == null;
        boolean endDayEmpty = endDay.getValue() == null;
        boolean hour1Empty = hour11.getValue() == null || hour12.getValue() == null;
        boolean hour2Empty = hour21.getValue() == null || hour22.getValue() == null;
        boolean minute1Empty = minute11.getValue() == null || minute12.getValue() == null;
        boolean minute2Empty = minute21.getValue() == null || minute22.getValue() == null;
        boolean second1Empty = second11.getValue() == null || second12.getValue() == null;
        boolean second2Empty = second21.getValue() == null || second22.getValue() == null;
        boolean descriptionEmpty = description.getText().isEmpty();
        Alert alert = new Alert(Alert.AlertType.ERROR);
        if (!nameEmpty && !typeEmpty && !startDayEmpty && !endDayEmpty && !hour1Empty && !hour2Empty
                && !minute1Empty && !minute2Empty && !second1Empty && !second2Empty && !descriptionEmpty) {
            String type1 = Objects.equals(type.getValue(), "竞赛") ? "CONTEST" : "VOLUNTEERING";
            String startHourStr = String.format("%02d", hour11.getValue()) + ":" + String.format("%02d", hour12.getValue()) + ":00";
            LocalDateTime startDateTime = LocalDateTime.of(startDay.getValue(), LocalTime.parse(startHourStr,
                    DateTimeFormatter.ofPattern("HH:mm:ss")));
            String endHourStr = String.format("%02d", hour21.getValue()) + ":" + String.format("%02d", hour22.getValue()) + ":00";
            LocalDateTime endDateTime = LocalDateTime.of(endDay.getValue(), LocalTime.parse(endHourStr,
                    DateTimeFormatter.ofPattern("HH:mm:ss")));
            JSONObject requestBody = new JSONObject();
            requestBody.put("name", name.getText());
            requestBody.put("type", type1);
            requestBody.put("start", startDateTime.toString());
            requestBody.put("end", endDateTime.toString());
            requestBody.put("description", description.getText());
            HttpResponse<JsonNode> response;
            if(type1.equals("CONTEST")){
                 response = HttpUtil.post(Globalvar.baseUrl + "/api/activities?type=contest")
                    .header("Content-Type", "application/json")
                    .body(requestBody)
                    .asJson();}
            else{
                   response = HttpUtil.post(Globalvar.baseUrl + "/api/activities?type=contest")
                        .header("Content-Type", "application/json")
                        .body(requestBody)
                        .asJson();}
                System.out.println("Response status: " +response.getStatus());
                System.out.println("Response body: " + response.getBody().toString());
                if(response.getStatus()==200){
                    JsonNode responseBody = response.getBody();
                    int id = responseBody.getObject().getInt("id");
                    alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("Success");
                    alert.setHeaderText(null);
                    alert.setContentText("注册成功!请上传图片");
                    Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
                    stage.setWidth(400);
                    stage.setHeight(200);
                    alert.showAndWait();
                    label.setVisible(true);
                    upload.setVisible(true);
                    submit1.setVisible(true);
                    Alert finalAlert = new Alert(Alert.AlertType.INFORMATION);
                    finalAlert.setTitle("Upload Image");
                    submit1.setOnMouseClicked(e->{
                        if(selectedFile == null){
                            finalAlert.setContentText("请上传图片！");
                            finalAlert.showAndWait();
                            return;
                        }
                        else {
                            HttpResponse res = HttpUtil.post(Globalvar.baseUrl + "/api/activities/" + id + "/poster")
                                    .field("file", new File(String.valueOf(selectedFile)))
                                    .asBytes();
                            System.out.println(res.getStatus());

                            if (res.getStatus() == 200) {
                                finalAlert.setContentText("上传图片成功！");
                                finalAlert.showAndWait();
                                name.clear();
                                type.getSelectionModel().clearSelection();
                                startDay.getEditor().clear();
                                endDay.getEditor().clear();
                                hour11.getSelectionModel().clearSelection();
                                hour12.getSelectionModel().clearSelection();
                                hour21.getSelectionModel().clearSelection();
                                hour22.getSelectionModel().clearSelection();
                                minute11.getSelectionModel().clearSelection();
                                minute12.getSelectionModel().clearSelection();
                                minute21.getSelectionModel().clearSelection();
                                minute22.getSelectionModel().clearSelection();
                                second11.getSelectionModel().clearSelection();
                                second12.getSelectionModel().clearSelection();
                                second21.getSelectionModel().clearSelection();
                                second22.getSelectionModel().clearSelection();
                                description.clear();
                                avatar.setImage(null);
                            } else {
                                finalAlert.setContentText("上传图片失败！");
                                finalAlert.showAndWait();
                            }
                        }});
                }
             else {
                alert.setTitle("Error");
                alert.setHeaderText(null);
                alert.setContentText("请完整填写活动信息！");
                Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
                stage.setWidth(400);
                stage.setHeight(200);
                alert.showAndWait();
            }
            }
}
}


